package com.jh.paymentchannel.service;

import java.math.BigDecimal;
import java.net.URI;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import cn.jh.common.tools.http.HttpClient;

import com.jh.paymentchannel.util.Base64;
import com.jh.paymentchannel.util.HttpUtil;
import com.jh.paymentchannel.util.MD5;
import com.jh.paymentchannel.util.Util;

@Service
public class ZFTGongZhongHaoTopupRequest implements TopupRequest{

	@Autowired
	Util util;
	

	@Override
	public Map<String, String> topupRequest(HttpServletRequest request,
			String amount, String ordercode, String orderdesc, String extra,
			String notifyurl, String returnurl, String channelParam)
			throws Exception {
		
		
		 /**判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		
		RestTemplate restTemplate=new RestTemplate();
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code",  ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		
		JSONObject jsonObject =  JSONObject.fromObject(result);
		JSONObject resultObj  =  jsonObject.getJSONObject("result");
		String openid  =  resultObj.getString("openid");

		JSONObject j = new JSONObject();
		j.put("merchantId", "0300059916");
		//j.put("merchantId", "0100000260");
		j.put("amount", new BigDecimal(amount).multiply(new BigDecimal("100")).toString());
		j.put("channelType",channelParam);
		j.put("orderId", ordercode);
		j.put("openId", openid);
		j.put("callBackUrl", notifyurl);
		String signature = "";
		if(channelParam.equalsIgnoreCase("WEIXIN")){
			j.put("appId", "wx964293b158c6e6af");
			signature = MD5.MD5Encode(j.get("merchantId").toString()+"|"+j.get("amount").toString()+"|"+j.get("channelType").toString()+"|"+j.get("openId").toString()+"|"+j.get("orderId").toString()+"|"+j.get("callBackUrl").toString()+"|"+j.get("appId").toString()+"|D3E91B3EC7010BB9697D58719896293D");
			
		}else{
			j.put("appId", "2017031606249487");
			signature = MD5.MD5Encode(j.get("merchantId").toString()+"|"+j.get("amount").toString()+"|"+j.get("channelType").toString()+"|"+j.get("openId").toString()+"|"+j.get("orderId").toString()+"|"+j.get("callBackUrl").toString()+"|"+j.get("appId").toString()+"|D3E91B3EC7010BB9697D58719896293D");
			
		}
		//String signature = MD5.MD5Encode(j.get("merchantId").toString()+"|"+j.get("amount").toString()+"|"+j.get("channelType").toString()+"|"+j.get("openId").toString()+"|"+j.get("orderId").toString()+"|"+j.get("callBackUrl").toString()+"|"+j.get("appId").toString()+"|85C2F265D07F3D54786846F8D9A56E8F");
		
		
		
		j.put("signature", signature);
		
		j.put("data", encode(j.toString()));
//		System.out.println(j.toString());
		String resultObjStr = HttpUtil.httpPost("http://119.23.116.209:8010/publicPay", j.toString());
		JSONObject obj  = JSONObject.fromObject(resultObjStr);
		String objresult =  obj.getString("payInfo");
		Map<String, String>  map = new HashMap<String, String>();
		map.put("resp_code", "success");	
        map.put("channel_type", "quick");
        map.put("redirect_url", objresult.toString());
        return map;
	}
	
	/*
	 public  String doPost(String apiUrl, Object json) {
	        CloseableHttpClient httpClient = HttpClients.createDefault();
	        String httpStr = null;
	        HttpPost httpPost = new HttpPost(apiUrl);
	        CloseableHttpResponse response = null;

	        try {
	            httpPost.setConfig(requestConfig);
	            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题  
	            stringEntity.setContentEncoding("UTF-8");
	            stringEntity.setContentType("application/json");
	            httpPost.setEntity(stringEntity);
	            response = httpClient.execute(httpPost);
	            HttpEntity entity = response.getEntity();
	            System.out.println(response.getStatusLine().getStatusCode());
	            httpStr = EntityUtils.toString(entity, "UTF-8");
	        } catch (IOException e) {
	             logger.error(e.getMessage(),e);
	        } finally {
	            if (response != null) {
	                try {
	                    EntityUtils.consume(response.getEntity());
	                } catch (IOException e) {
	                    logger.error(e.getMessage(),e);
	                }
	            }
	        }
	        return httpStr;
	    }*/

	
	
	
	public  String encode(String plainText) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRwrqwknhOA44knSjvQ2NvaXzpDc3n607NAC6pfZdtIz1N06VZBPiVxzBtvQMSB+4H72GsS00NgzE7CGxWVfLx7c/4m3F5rDeaqAotdiAFcAdUWCerqN9175QvExgISsEbKERxly50ZHQUxJBuAdbozCbeeqB+SGQMpzeAqYyRFwIDAQAB".getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec("01234567".getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] encryptData = cipher.doFinal(plainText.getBytes("UTF-8"));
        return Base64.encode(encryptData);
    }

	

}
